/*
 *  Copyright 2010 Alexey Frishman (alexey.frishman@gmail.com)
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License"); you may not
 *  use this file except in compliance with the License. You may obtain a copy of
 *  the License at
 *  
 *  http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 *  License for the specific language governing permissions and limitations under
 *  the License.
 * 
 */

package org.json4g.serialization.policy.jaxb;

import javax.xml.bind.annotation.XmlElement;

import org.json4g.serialization.policy.FieldNamePolicy;

import com.gwtent.reflection.client.ClassType;
import com.gwtent.reflection.client.Field;

/**
 * Extracts name for field, taking into account XmlElement(name=...) attribute
 */
public class JaxbFieldNamePolicy implements FieldNamePolicy {

    /**
     * @return If @XmlElement(name=...) attribute is present, then the value of the attribute. Otherwise - usual Java field name.
     */
    @Override
    public String getNameForField(Field field) {
        String result;
        XmlElement annotation = field.getAnnotation(XmlElement.class);
        if (annotation != null && !annotation.name().equals("##default")) {
            result = annotation.name();
        } else {
            result = field.getName();
        }
        return result;
    }

    /**
     * First of all looks for the Java field name equal to the given one.
     * If not found, then looks for a field with @XmlElement(name=...) attribute. If nothing found, returns null;
     */
    @Override
    public Field getFieldByName(ClassType type, String name) {
        Field result = type.getField(name);
        if (result == null) {
            for (Field field : type.getFields()) {
                XmlElement annotation = field.getAnnotation(XmlElement.class);
                if (annotation != null && !annotation.name().equals("##default") && name.equals(annotation.name())) {
                    result = field;
                    break;
                }
            }
        }
        return result;
    }

}
